const { app, BrowserWindow, Tray, Menu, ipcMain, screen, dialog } = require('electron');
const path = require('path');
const fs = require('fs');

// 保持对窗口的全局引用
let widgets = [];
let tray = null;

// 引入数据库管理器
const databaseManager = require('./database');

// 当Electron完成初始化并准备创建浏览器窗口时调用此方法
app.whenReady().then(() => {
  // 初始化数据库
  databaseManager.init(app);
  
  createWidget();
  createTray();
});

// 创建挂件窗口的函数
function createWidget(x, y) {
  const primaryDisplay = screen.getPrimaryDisplay();
  const { width, height } = primaryDisplay.workAreaSize;
  
  // 确保坐标在屏幕范围内
  const widgetX = x !== undefined ? x : width - 350;
  const widgetY = y !== undefined ? y : height - 450;
  
  // 创建浏览器窗口
  const widget = new BrowserWindow({
    x: widgetX,
    y: widgetY,
    width: 300,
    height: 400,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    },
    // 无边框窗口
    frame: false,
    // 透明背景
    transparent: true,
    // 始终置顶
    alwaysOnTop: true,
    // 跳过任务栏
    skipTaskbar: true
  });

  // 加载index.html文件
  widget.loadFile('src/index.html');

  // 打开开发者工具
  // widget.webContents.openDevTools();

  // 当窗口关闭时触发
  widget.on('closed', function () {
    // 从数组中移除窗口引用
    const index = widgets.indexOf(widget);
    if (index > -1) {
      widgets.splice(index, 1);
    }
  });
  
  // 将新窗口添加到数组中
  widgets.push(widget);
  
  return widget;
}

// 创建系统托盘
function createTray() {
  try {
    const { nativeImage } = require('electron');
    
    // 首先初始化tray为null
    tray = null;
    
    // 根据不同平台创建合适的图标，不依赖第三方模块
    if (process.platform === 'win32') {
      // Windows平台: 尝试多种方式创建托盘
      try {
        // 方案1: 使用Base64编码的简单图标（16x16px）
        const base64Icon = 'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAAsTAAALEwEAmpwYAAABlUlEQVR4nK2TxQ7CMAyFv5GJwUlYhBC7D4dP17GpQ0QVdF67mYI7W9w5GfZ+O6D6D5Z+P5P5W9X9n73QKvH2r8D4JnC5uU5g5K5s5a5f5Y1q422P6X6e6b6m6v639X5z5l5j5Z5X5N5O5M5K5J5H5F5D5B5A58565452505/4v4n4j4G4E4C4A49474543414/3v3n3j3G3E3C3A39373533313/2v2n2j2G2E2C2A29272523212/1v1n1j1G1E1C1A19171513111/+w+t+P+J+D+C+A+9+7+5+3+1+/w/t/P/J/D/C/A/9/7/5/3/1//wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP4b9E8AAAAASUVORK5CYII=';
        const icon = nativeImage.createFromDataURL(`data:image/png;base64,${base64Icon}`);
        tray = new Tray(icon);
        console.log('Windows Base64 PNG图标创建成功');
      } catch (imgError) {
        console.error('Windows Base64 PNG图标创建失败:', imgError.message);
        
        try {
          // 方案2: 尝试使用简单的SVG图标
          const svgContent = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"><circle cx="8" cy="8" r="8" fill="%233B82F6"/><circle cx="8" cy="8" r="4" fill="white"/></svg>';
          const base64Svg = Buffer.from(svgContent).toString('base64');
          const icon = nativeImage.createFromDataURL(`data:image/svg+xml;base64,${base64Svg}`);
          tray = new Tray(icon);
          console.log('Windows SVG图标创建成功');
        } catch (svgError) {
          console.error('Windows SVG图标创建失败:', svgError.message);
          
          try {
            // 方案3: 使用临时文件创建图标
            const tempDir = require('os').tmpdir();
            const tempFilePath = path.join(tempDir, 'tray-icon.txt');
            fs.writeFileSync(tempFilePath, '📝');
            tray = new Tray(tempFilePath);
            fs.unlinkSync(tempFilePath);
            console.log('Windows临时文件图标创建成功');
          } catch (fileError) {
            console.error('Windows临时文件图标创建失败:', fileError.message);
            
            try {
              // 方案4: 使用空图标作为最后的备选方案
              tray = new Tray(nativeImage.createEmpty());
              console.log('使用空图标作为最后的备选方案');
            } catch (emptyError) {
              console.error('创建空图标也失败:', emptyError.message);
            }
          }
        }
      }
    } else if (process.platform === 'darwin') {
      // macOS平台: 使用简单的SVG文本图标
      try {
        const svgContent = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"><circle cx="8" cy="8" r="8" fill="%233B82F6"/><circle cx="8" cy="8" r="4" fill="white"/></svg>';
        const base64Svg = Buffer.from(svgContent).toString('base64');
        const icon = nativeImage.createFromDataURL(`data:image/svg+xml;base64,${base64Svg}`);
        tray = new Tray(icon);
        console.log('macOS SVG图标创建成功');
      } catch (macError) {
        console.error('macOS图标创建失败:', macError.message);
        try {
          tray = new Tray(nativeImage.createEmpty());
          console.log('macOS使用空图标作为备选方案');
        } catch (emptyError) {
          console.error('macOS创建空图标也失败:', emptyError.message);
        }
      }
    } else {
      // Linux平台: 使用简单的文本图标
      try {
        const tempDir = require('os').tmpdir();
        const tempFilePath = path.join(tempDir, 'tray-icon.txt');
        fs.writeFileSync(tempFilePath, '📝');
        tray = new Tray(tempFilePath);
        fs.unlinkSync(tempFilePath);
        console.log('Linux临时文件图标创建成功');
      } catch (linuxError) {
        console.error('Linux图标创建失败:', linuxError.message);
        try {
          tray = new Tray(nativeImage.createEmpty());
          console.log('Linux使用空图标作为备选方案');
        } catch (emptyError) {
          console.error('Linux创建空图标也失败:', emptyError.message);
        }
      }
    }
    
    // 如果成功创建了托盘，设置工具提示和菜单
    if (tray) {
      try {
        tray.setToolTip('桌面挂件应用');
        
        // 创建系统托盘菜单
        const contextMenu = Menu.buildFromTemplate([
          { label: '新建挂件', click: () => { createWidget(); } },
          { label: '显示所有', click: showAllWidgets },
          { label: '隐藏所有', click: hideAllWidgets },
          { label: '最小化所有', click: () => {
            widgets.forEach(widget => {
              widget.minimize();
            });
          }},
          { label: '打开设置', click: () => { createSettingsWindow(); } },
          { label: '退出', click: () => { app.quit(); } }
        ]);
        tray.setContextMenu(contextMenu);
        console.log('系统托盘菜单设置成功');
        
        // 设置双击忽略和点击事件
        tray.setIgnoreDoubleClickEvents(true);
        tray.on('click', () => {
          if (widgets.length === 0) {
            createWidget();
          } else {
            toggleAllWidgets();
          }
        });
      } catch (menuError) {
        console.error('设置系统托盘菜单失败:', menuError.message);
      }
    }
  } catch (error) {
    console.log('无法创建系统托盘:', error.message);
    // 如果无法创建托盘，继续运行应用
  }
}

// 显示所有挂件
function showAllWidgets() {
  widgets.forEach(widget => {
    widget.show();
  });
}

// 隐藏所有挂件
function hideAllWidgets() {
  widgets.forEach(widget => {
    widget.hide();
  });
}

// 切换所有挂件的显示/隐藏
function toggleAllWidgets() {
  if (widgets.length > 0 && widgets[0].isVisible()) {
    hideAllWidgets();
  } else {
    showAllWidgets();
  }
}

// 当所有窗口都关闭时退出应用
app.on('window-all-closed', function () {
  // 在macOS上，应用程序和它们的菜单栏通常保持活动状态，直到用户明确退出
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', function () {
  // 在macOS上，当单击停靠图标且没有其他窗口打开时，通常会重新创建一个窗口
  if (widgets.length === 0) {
    createWidget();
  }
});

// IPC处理程序
ipcMain.on('close-widget', (event) => {
  const webContents = event.sender;
  const widget = BrowserWindow.fromWebContents(webContents);
  widget.hide();
});

ipcMain.on('minimize-widget', (event) => {
  const webContents = event.sender;
  const widget = BrowserWindow.fromWebContents(webContents);
  widget.minimize();
});

ipcMain.on('create-new-widget', () => {
  createWidget();
});

ipcMain.on('delete-widget', (event) => {
  const webContents = event.sender;
  const widget = BrowserWindow.fromWebContents(webContents);
  widget.close();
});

// 处理窗口移动
ipcMain.on('move-widget', (event, { x, y }) => {
  const webContents = event.sender;
  const widget = BrowserWindow.fromWebContents(webContents);
  if (widget) {
    // 获取当前窗口位置
    const [currentX, currentY] = widget.getPosition();
    // 计算新位置（相对于当前窗口位置）
    const newX = currentX + x;
    const newY = currentY + y;
    widget.setPosition(Math.round(newX), Math.round(newY));
  }
});

// 处理窗口调整大小
ipcMain.on('resize-widget', (event, { width, height }) => {
  const webContents = event.sender;
  const widget = BrowserWindow.fromWebContents(webContents);
  if (widget) {
    widget.setSize(Math.round(width), Math.round(height));
    
    // 通知窗口调整大小已完成
    setTimeout(() => {
      webContents.send('widget-resized', { width: Math.round(width), height: Math.round(height) });
    }, 100);
  }
});

// 处理设置相关
let settingsWindow = null;

function createSettingsWindow() {
  if (settingsWindow) {
    settingsWindow.focus();
    return;
  }
  
  settingsWindow = new BrowserWindow({
    width: 500,
    height: 600,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    },
    resizable: false,
    fullscreenable: false
  });
  
  settingsWindow.loadFile('src/settings.html');
  
  settingsWindow.on('closed', () => {
    settingsWindow = null;
  });
}

ipcMain.on('open-settings', () => {
  createSettingsWindow();
});

ipcMain.on('apply-settings', (event, settings) => {
  // 将设置应用到所有挂件
  widgets.forEach(widget => {
    // 通知挂件更新设置
    widget.webContents.send('settings-updated', settings);
    
    // 如果设置了窗口穿透，应用窗口穿透设置
    if (settings.clickThrough) {
      widget.setIgnoreMouseEvents(true);
    } else {
      widget.setIgnoreMouseEvents(false);
    }
    
    // 如果设置了置顶状态，应用置顶设置
    widget.setAlwaysOnTop(settings.alwaysOnTop);
    
    // 更新窗口透明度
    widget.setOpacity(settings.opacity);
  });
  
  // 保存设置到文件系统，以便关闭设置窗口时可以重新应用
  const userDataPath = app.getPath('userData');
  const settingsPath = path.join(userDataPath, 'settings.json');
  
  try {
    fs.writeFileSync(settingsPath, JSON.stringify(settings), 'utf8');
  } catch (error) {
    console.error('保存设置失败:', error);
  }
  
  // 通知设置窗口设置已应用
  event.sender.send('settings-applied');
});

ipcMain.on('close-settings', () => {
  if (settingsWindow) {
    settingsWindow.close();
  }
  
  // 重新应用保存的设置，确保点击穿透状态正确
  const userDataPath = app.getPath('userData');
  const settingsPath = path.join(userDataPath, 'settings.json');
  
  try {
    if (fs.existsSync(settingsPath)) {
      const savedSettings = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
      widgets.forEach(widget => {
        // 确保点击穿透设置正确应用
        if (savedSettings.clickThrough) {
          widget.setIgnoreMouseEvents(true);
        } else {
          widget.setIgnoreMouseEvents(false);
        }
      });
    }
  } catch (error) {
    console.error('读取保存的设置失败:', error);
  }
});

// 处理数据库路径浏览请求
ipcMain.on('browse-db-path', (event) => {
  const { dialog } = require('electron');
  
  dialog.showOpenDialog(settingsWindow, {
    title: '选择数据库保存目录',
    properties: ['openDirectory'],
    defaultPath: process.cwd()
  }).then(result => {
    if (!result.canceled && result.filePaths.length > 0) {
      event.sender.send('db-path-selected', result.filePaths[0]);
    }
  }).catch(err => {
    console.error('选择目录对话框错误:', err);
  });
});

// 处理获取当前数据库路径请求
ipcMain.on('get-current-db-path', (event) => {
  event.sender.send('current-db-path', databaseManager.dbPath);
});

// 修改apply-settings事件处理，添加数据库路径变更处理
const originalApplySettingsHandler = ipcMain.listeners('apply-settings')[0];
ipcMain.removeAllListeners('apply-settings');
ipcMain.on('apply-settings', (event, settings) => {
  // 检查是否需要更改数据库路径
  if (settings.dbPath && settings.dbPath !== databaseManager.dbPath) {
    // 不再显示警告对话框，直接处理数据库路径变更
    try {
        try {
          // 关闭当前数据库连接
          if (databaseManager.db) {
            databaseManager.db.close();
          }
          
          // 设置新的数据库路径
          databaseManager.dbPath = path.join(settings.dbPath, 'tasks.db');
          
          // 重新初始化数据库
          const sqlite3 = require('sqlite3').verbose();
          databaseManager.db = new sqlite3.Database(databaseManager.dbPath, (err) => {
            if (err) {
              console.error('数据库连接失败:', err);
              databaseManager.db = null;
              // 显示错误消息
              dialog.showErrorBox('错误', '无法连接到新的数据库路径');
            } else {
              console.log('数据库连接成功，新路径:', databaseManager.dbPath);
              // 重新创建表
              databaseManager.createTables();
              // 通知用户
              dialog.showMessageBox(settingsWindow, {
                type: 'info',
                title: '成功',
                message: '数据库路径已更改为: ' + databaseManager.dbPath
              });
              
              // 刷新所有挂件的任务列表
              databaseManager.getTodayTasks((err, todayTasks) => {
                if (!err) {
                  widgets.forEach(widget => {
                    widget.webContents.send('tasks-updated', todayTasks);
                  });
                }
              });
              
              // 刷新任务管理窗口的任务列表
              if (taskManagerWindow) {
                databaseManager.getAllTasks((err, allTasks) => {
                  if (!err) {
                    taskManagerWindow.webContents.send('tasks-updated', allTasks);
                  }
                });
              }
            }
          });
        } catch (error) {
          console.error('更改数据库路径失败:', error);
          dialog.showErrorBox('错误', '更改数据库路径失败: ' + error.message);
        }
    } catch (error) {
      console.error('处理数据库路径变更失败:', error);
    }
    
    // 调用原始的应用设置处理函数
    originalApplySettingsHandler(event, settings);
  } else {
    // 没有更改数据库路径，直接应用其他设置
    originalApplySettingsHandler(event, settings);
  }
});

// 处理状态管理相关
let statusManagerWindow = null;
let currentStatus = { id: 1, name: '工作中', color: '#28a745', description: '正在专注工作' };

// 获取所有状态数据
function getAllStatuses(callback) {
  databaseManager.getAllStatuses((err, statuses) => {
    if (err) {
      callback(err, null);
      return;
    }
    
    const defaultStatuses = statuses.filter(status => status.is_default === 1);
    const customStatuses = statuses.filter(status => status.is_default === 0);
    
    callback(null, {
      default: defaultStatuses,
      custom: customStatuses,
      current: currentStatus
    });
  });
}

function createStatusManagerWindow() {
  if (statusManagerWindow) {
    statusManagerWindow.focus();
    return;
  }
  
  statusManagerWindow = new BrowserWindow({
    width: 700,
    height: 400,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    },
    resizable: false,
    fullscreenable: false
  });
  
  statusManagerWindow.loadFile('src/statusManager.html');
  
  statusManagerWindow.on('closed', () => {
    statusManagerWindow = null;
  });
}

ipcMain.on('open-status-manager', () => {
  createStatusManagerWindow();
  if (statusManagerWindow) {
    statusManagerWindow.webContents.once('dom-ready', () => {
      getAllStatuses((err, statusData) => {
        if (!err) {
          statusManagerWindow.webContents.send('status-data', statusData);
        }
      });
    });
  }
});

ipcMain.on('get-status-data', (event) => {
  getAllStatuses((err, statusData) => {
    if (!err) {
      event.sender.send('status-data', statusData);
    }
  });
});

ipcMain.on('set-current-status', (event, status) => {
  currentStatus = status;
  // 通知所有挂件更新状态
  widgets.forEach(widget => {
    widget.webContents.send('update-current-status', status);
  });
  
  // 更新状态管理窗口
  if (statusManagerWindow) {
    getAllStatuses((err, statusData) => {
      if (!err) {
        statusManagerWindow.webContents.send('status-updated', statusData);
      }
    });
  }
  
  // 同步数据到分享页面
  syncSharedData();
});

ipcMain.on('add-custom-status', (event, statusData) => {
  databaseManager.addCustomStatus(statusData, (err) => {
    if (err) {
      console.error('添加自定义状态失败:', err);
      return;
    }
    
    // 获取更新后的状态数据
    getAllStatuses((err, statusData) => {
      if (!err) {
        // 设置新增的状态为当前状态
        const addedStatus = statusData.custom.find(s => s.name === statusData.name);
        if (addedStatus) {
          currentStatus = addedStatus;
          
          // 通知所有挂件更新当前状态
          widgets.forEach(widget => {
            widget.webContents.send('update-current-status', currentStatus);
          });
          
          // 同步数据到分享页面
          syncSharedData();
        }
        
        // 更新状态管理窗口
        if (statusManagerWindow) {
          statusManagerWindow.webContents.send('status-updated', statusData);
        }
        
        // 通知所有挂件更新状态列表
        widgets.forEach(widget => {
          widget.webContents.send('status-list-updated', statusData);
        });
      }
    });
  });
});

ipcMain.on('delete-custom-status', (event, id) => {
  databaseManager.deleteCustomStatus(id, (err) => {
    if (err) {
      console.error('删除自定义状态失败:', err);
      return;
    }
    
    // 获取更新后的状态数据
    getAllStatuses((err, statusData) => {
      if (!err) {
        // 如果删除的是当前状态，则切换到默认状态
        if (currentStatus.id === id) {
          if (statusData.default.length > 0) {
            currentStatus = statusData.default[0];
            // 通知所有挂件更新状态
            widgets.forEach(widget => {
              widget.webContents.send('update-current-status', currentStatus);
            });
            
            // 同步数据到分享页面
            syncSharedData();
          }
        }
        
        // 更新状态管理窗口
        if (statusManagerWindow) {
          statusManagerWindow.webContents.send('status-updated', statusData);
        }
      }
    });
  });
});

ipcMain.on('close-status-manager', () => {
  if (statusManagerWindow) {
    statusManagerWindow.close();
  }
});

// 处理任务管理相关
let taskManagerWindow = null;

function createTaskManagerWindow() {
  if (taskManagerWindow) {
    taskManagerWindow.focus();
    return;
  }
  
  taskManagerWindow = new BrowserWindow({
    width: 900,
    height: 700,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    },
    resizable: true,
    fullscreenable: false
  });
  
  taskManagerWindow.loadFile('src/taskManager.html');
  
  taskManagerWindow.on('closed', () => {
    taskManagerWindow = null;
  });
}

ipcMain.on('open-task-manager', () => {
  createTaskManagerWindow();
  if (taskManagerWindow) {
    taskManagerWindow.webContents.once('dom-ready', () => {
      databaseManager.getAllTasks((err, tasks) => {
        if (err) {
          console.error('获取任务数据失败:', err);
          taskManagerWindow.webContents.send('task-data', []);
        } else {
          taskManagerWindow.webContents.send('task-data', tasks);
        }
      });
    });
  }
});

ipcMain.on('get-task-data', (event) => {
  databaseManager.getAllTasks((err, tasks) => {
    if (err) {
      console.error('获取任务数据失败:', err);
      event.sender.send('task-data', []);
    } else {
      event.sender.send('task-data', tasks);
    }
  });
});

ipcMain.on('get-today-tasks', (event) => {
  databaseManager.getTodayTasks((err, tasks) => {
    if (err) {
      console.error('获取今日任务数据失败:', err);
      event.sender.send('task-data', []);
    } else {
      event.sender.send('task-data', tasks);
    }
  });
});

ipcMain.on('add-task', (event, taskData) => {
  databaseManager.addTask(taskData, (err) => {
    if (err) {
      console.error('添加任务失败:', err);
      return;
    }
    
    // 获取更新后的任务列表
    databaseManager.getAllTasks((err, tasks) => {
      if (!err) {
        // 更新任务管理窗口
        if (taskManagerWindow) {
          taskManagerWindow.webContents.send('tasks-updated', tasks);
        }
        
        // 获取今日任务并通知所有挂件更新
        databaseManager.getTodayTasks((err, todayTasks) => {
          if (!err) {
            // 通知所有挂件更新今日任务列表
            widgets.forEach(widget => {
              widget.webContents.send('tasks-updated', todayTasks);
            });
          }
        });
        
        // 同步数据到分享页面
        syncSharedData();
      }
    });
  });
});

ipcMain.on('update-task', (event, { id, updates }) => {
  databaseManager.updateTask(id, updates, (err) => {
    if (err) {
      console.error('更新任务失败:', err);
      return;
    }
    
    // 获取更新后的任务列表
    databaseManager.getAllTasks((err, tasks) => {
      if (!err) {
        // 更新任务管理窗口
        if (taskManagerWindow) {
          taskManagerWindow.webContents.send('tasks-updated', tasks);
        }
        
        // 获取今日任务并通知所有挂件更新
        databaseManager.getTodayTasks((err, todayTasks) => {
          if (!err) {
            // 通知所有挂件更新今日任务列表
            widgets.forEach(widget => {
              widget.webContents.send('tasks-updated', todayTasks);
            });
          }
        });
        
        // 同步数据到分享页面
        syncSharedData();
      }
    });
  });
});

ipcMain.on('delete-task', (event, id) => {
  databaseManager.deleteTask(id, (err) => {
    if (err) {
      console.error('删除任务失败:', err);
      return;
    }
    
    // 获取更新后的任务列表
    databaseManager.getAllTasks((err, tasks) => {
      if (!err) {
        // 更新任务管理窗口
        if (taskManagerWindow) {
          taskManagerWindow.webContents.send('tasks-updated', tasks);
        }
        
        // 获取今日任务并通知所有挂件更新
        databaseManager.getTodayTasks((err, todayTasks) => {
          if (!err) {
            // 通知所有挂件更新今日任务列表
            widgets.forEach(widget => {
              widget.webContents.send('tasks-updated', todayTasks);
            });
          }
        });
        
        // 同步数据到分享页面
        syncSharedData();
      }
    });
  });
});

ipcMain.on('toggle-task-status', (event, id) => {
  // 先获取任务当前状态，然后更新
  databaseManager.getAllTasks((err, tasks) => {
    if (!err) {
      const task = tasks.find(t => t.id === id);
      if (task) {
        const statusOrder = ['pending', 'in-progress', 'completed'];
        const currentIndex = statusOrder.indexOf(task.status);
        const nextIndex = (currentIndex + 1) % statusOrder.length;
        const newStatus = statusOrder[nextIndex];
        
        // 更新任务状态
        databaseManager.updateTask(id, { status: newStatus }, (err) => {
          if (!err) {
            // 获取更新后的任务列表
            databaseManager.getAllTasks((err, updatedTasks) => {
              if (!err) {
                // 更新任务管理窗口
                if (taskManagerWindow) {
                  taskManagerWindow.webContents.send('tasks-updated', updatedTasks);
                }
                
                // 获取今日任务并通知所有挂件更新
                databaseManager.getTodayTasks((err, todayTasks) => {
                  if (!err) {
                    // 通知所有挂件更新今日任务列表
                    widgets.forEach(widget => {
                      widget.webContents.send('tasks-updated', todayTasks);
                    });
                  }
                });
                
                // 同步数据到分享页面
                syncSharedData();
              }
            });
          }
        });
      }
    }
  });
});

ipcMain.on('close-task-manager', () => {
  if (taskManagerWindow) {
    taskManagerWindow.close();
  }
});

// 处理报告生成相关
let reportGeneratorWindow = null;

function createReportGeneratorWindow() {
  if (reportGeneratorWindow) {
    reportGeneratorWindow.focus();
    return;
  }
  
  reportGeneratorWindow = new BrowserWindow({
    width: 900,
    height: 700,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    },
    resizable: true,
    fullscreenable: false
  });
  
  reportGeneratorWindow.loadFile('src/reportGenerator.html');
  
  reportGeneratorWindow.on('closed', () => {
    reportGeneratorWindow = null;
  });
}

ipcMain.on('open-report-generator', (event, reportType = 'daily') => {
  createReportGeneratorWindow();
  if (reportGeneratorWindow) {
    reportGeneratorWindow.webContents.once('dom-ready', () => {
      // 发送用户信息、状态和任务数据到报告生成窗口
      databaseManager.getUserInfo((err, userInfo) => {
        if (err) {
          userInfo = { name: '', department: '', position: '' };
        }
        
        databaseManager.getAllTasks((err, tasks) => {
          if (err) {
            tasks = [];
          }
          
          reportGeneratorWindow.webContents.send('report-data', {
            userInfo: userInfo || { name: '', department: '', position: '' },
            status: currentStatus,
            tasks: tasks,
            reportType: reportType
          });
        });
      });
    });
  }
});

ipcMain.on('get-report-data', (event, reportType = 'daily') => {
  // 获取用户信息
  databaseManager.getUserInfo((err, userInfo) => {
    if (err) {
      userInfo = { name: '', department: '', position: '' };
    }
    
    // 获取所有任务
    databaseManager.getAllTasks((err, tasks) => {
      if (err) {
        tasks = [];
      }
      
      event.sender.send('report-data', {
        userInfo: userInfo || { name: '', department: '', position: '' },
        status: currentStatus,
        tasks: tasks,
        reportType: reportType
      });
    });
  });
});

// 处理局域网分享相关
let shareManagerWindow = null;
let isSharing = false;
let networkManager = null;

function createShareManagerWindow() {
  if (shareManagerWindow) {
    shareManagerWindow.focus();
    return;
  }
  
  shareManagerWindow = new BrowserWindow({
    width: 600,
    height: 400,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    },
    resizable: false,
    fullscreenable: false
  });
  
  shareManagerWindow.loadFile('src/shareManager.html');
  
  shareManagerWindow.on('closed', () => {
    shareManagerWindow = null;
  });
}

ipcMain.on('open-share-manager', () => {
  createShareManagerWindow();
  if (shareManagerWindow) {
    shareManagerWindow.webContents.once('dom-ready', () => {
      // 发送分享状态到分享管理窗口
      shareManagerWindow.webContents.send('share-status', {
        isSharing: isSharing,
        serverInfo: isSharing ? networkManager.getServerStatus() : null
      });
    });
  }
});

ipcMain.on('start-sharing', async (event, userInfo) => {
  try {
    // 动态导入网络管理模块并赋值给全局变量
    if (!networkManager) {
      networkManager = require('./networkManager');
    }
    
    // 更新用户信息
    if (userInfo) {
      databaseManager.updateUserInfo(userInfo, (err) => {
        if (err) {
          console.error('更新用户信息失败:', err);
        }
      });
    }
    
    // 启动服务器
    await networkManager.startServer();
    
    // 更新共享数据
    // 获取所有任务
    databaseManager.getAllTasks((err, tasks) => {
      if (err) {
        tasks = [];
      }
      
      networkManager.updateSharedData({
        userInfo: userInfo,
        status: currentStatus,
        tasks: tasks
      });
    });
    
    isSharing = true;
    
    // 获取完整的服务器状态信息，包含URL
    const serverStatus = networkManager.getServerStatus();
    
    // 通知所有窗口分享已开始
    widgets.forEach(widget => {
      widget.webContents.send('sharing-started', serverStatus);
    });
    
    // 通知分享管理窗口
    if (shareManagerWindow) {
      shareManagerWindow.webContents.send('share-status', {
        isSharing: true,
        serverInfo: serverStatus
      });
    }
    
    // 发送成功消息
    event.sender.send('sharing-started', serverStatus);
  } catch (error) {
    console.error('启动分享失败:', error);
    event.sender.send('sharing-error', error.message);
  }
});

ipcMain.on('stop-sharing', (event) => {
  if (networkManager && isSharing) {
    networkManager.stopServer();
    isSharing = false;
    
    // 通知所有窗口分享已停止
    widgets.forEach(widget => {
      widget.webContents.send('sharing-stopped');
    });
    
    // 通知分享管理窗口
    if (shareManagerWindow) {
      shareManagerWindow.webContents.send('share-status', {
        isSharing: false,
        serverInfo: null
      });
    }
    
    event.sender.send('sharing-stopped');
  }
});

ipcMain.on('get-share-status', (event) => {
  event.sender.send('share-status', {
    isSharing: isSharing,
    serverInfo: isSharing && networkManager ? networkManager.getServerStatus() : null
  });
});

ipcMain.on('close-share-manager', () => {
  if (shareManagerWindow) {
    shareManagerWindow.close();
  }
});

// 当状态或任务更新时，同步到网络管理器
function syncSharedData() {
  if (networkManager && isSharing) {
    // 获取所有任务
    databaseManager.getAllTasks((err, tasks) => {
      if (!err) {
        networkManager.updateSharedData({
          status: currentStatus,
          tasks: tasks
        });
      }
    });
  }
}

// 监听状态和任务更新，同步到网络管理器
function updateCurrentStatus(status) {
  currentStatus = status;
  syncSharedData();
}

ipcMain.on('export-report-as-text', (event, { content, filename }) => {
  const { dialog } = require('electron');
  const fs = require('fs');
  const path = require('path');
  
  dialog.showSaveDialog(reportGeneratorWindow, {
    title: '导出报告为文本',
    defaultPath: filename,
    filters: [
      { name: '文本文件', extensions: ['txt'] },
      { name: '所有文件', extensions: ['*'] }
    ]
  }).then(result => {
    if (!result.canceled && result.filePath) {
      fs.writeFile(result.filePath, content, 'utf8', (err) => {
        if (err) {
          console.error('保存文件失败:', err);
          dialog.showErrorBox('错误', '保存文件失败');
        } else {
          dialog.showMessageBox(reportGeneratorWindow, {
            type: 'info',
            title: '成功',
            message: '报告已成功导出'
          });
        }
      });
    }
  }).catch(err => {
    console.error('保存对话框错误:', err);
  });
});

ipcMain.on('export-report-as-md', (event, { content, filename }) => {
  const { dialog } = require('electron');
  const fs = require('fs');
  
  dialog.showSaveDialog(reportGeneratorWindow, {
    title: '导出报告为Markdown',
    defaultPath: filename,
    filters: [
      { name: 'Markdown文件', extensions: ['md'] },
      { name: '所有文件', extensions: ['*'] }
    ]
  }).then(result => {
    if (!result.canceled && result.filePath) {
      fs.writeFile(result.filePath, content, 'utf8', (err) => {
        if (err) {
          console.error('保存文件失败:', err);
          dialog.showErrorBox('错误', '保存文件失败');
        } else {
          dialog.showMessageBox(reportGeneratorWindow, {
            type: 'info',
            title: '成功',
            message: '报告已成功导出'
          });
        }
      });
    }
  }).catch(err => {
    console.error('保存对话框错误:', err);
  });
});

ipcMain.on('close-report-generator', () => {
  if (reportGeneratorWindow) {
    reportGeneratorWindow.close();
  }
});